package com.atguigu.threadtest;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ClassName: TryLockTest
 * Package: com.atguigu
 * Description:
 *
 * @author: fu-wang
 * @create: 2024/10/28 19:18
 * version: 1.0
 */
public class DeadLock {
    //死锁测试
    private final static ReentrantLock lock1 = new ReentrantLock();
    private final static ReentrantLock lock2 = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(()->{
            boolean lock = lock1.tryLock();

            if (lock){
                try {

                    System.out.println("lock1...");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("lock1 -> lock2");
                    boolean b = lock2.tryLock();
                    if (b) {
                        try {
                            System.out.println("lock2----");
                        }finally {
                            lock2.unlock();
                        }
                    }
                }finally {
                    lock1.unlock();
                }
            }else {
                System.out.println("lock1未获取");
            }

        }).start();
        new Thread(() -> {

            boolean result2 = lock2.tryLock();

            if(result2){
                try {

                    System.out.println("Thread 2: Holding lock 2...");
                    try {
                        Thread.sleep(500); // Simulate some work
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Thread 2: Waiting for lock 1...");


                    boolean result1 = lock1.tryLock();
                    if(result1){
                        try {
                            System.out.println("Thread 2: Both locks acquired.");
                        } finally {
                            lock1.unlock();
                        }
                    }else {
                        System.out.println("Thread 2: 未获取到锁1");
                    }
                }finally {
                    lock2.unlock();
                }
            }else{
                System.out.println("Thread 2: 未获取到锁2");
            }

        }).start();
    }
}
